layui.define(['jquery', 'table', 'form', 'layer'], function(exports) {
    var $ = layui.jquery, 
        table = layui.table, 
        form = layui.form, 
        layer = layui.layer;

    var tableIns;

    function init() {
        renderTable();
        bindEvents();
    }

    function renderTable() {
        // 渲染表格
        tableIns = table.render({
            elem: '#userTable',
            url: '/user/list',
            method: 'get',
            toolbar: '#userToolbar',
            defaultToolbar: ['filter', 'exports', 'print'],
            parseData: function(res) {
                return {
                    "code": res.code === 200 ? 0 : res.code,
                    "msg": res.message,
                    "count": res.data ? res.data.total : 0,
                    "data": res.data ? res.data.records : []
                };
            },
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {field: 'id', title: 'ID', width: 80, sort: true},
                {field: 'username', title: '用户名', width: 120},
                {field: 'realName', title: '真实姓名', width: 100},
                {field: 'phone', title: '手机号', width: 120},
                {field: 'email', title: '邮箱', width: 150},
                {field: 'gender', title: '性别', width: 80, templet: function(d) {
                    return d.gender === 1 ? '男' : '女';
                }},
                {field: 'status', title: '状态', width: 80, templet: function(d) {
                    return d.status === 1 ? '启用' : '禁用';
                }},
                {field: 'role', title: '角色', width: 80, templet: function(d) {
                    var roleMap = {0: '普通用户', 1: '管理员'};
                    return roleMap[d.role] || '未知';
                }},
                {field: 'address', title: '地址', width: 150},
                {field: 'lastLoginTime', title: '最后登录时间', width: 150, templet: function(d) {
                    return d.lastLoginTime ? new Date(d.lastLoginTime).toLocaleString() : '';
                }},
                {title: '操作', width: 200, align: 'center', fixed: 'right', toolbar: '#userBar'}
            ]],
            page: true,
            limit: 10,
            limits: [10, 20, 50, 100]
        });
    }

    function bindEvents() {
        // 搜索按钮
        form.on('submit(userSearch)', function(data) {
            tableIns.reload({
                where: data.field,
                page: {curr: 1}
            });
            return false;
        });

        // 重置按钮
        $('#userReset').on('click', function() {
            $('#userSearchForm')[0].reset();
            tableIns.reload({
                where: {},
                page: {curr: 1}
            });
        });

        // 新增按钮
        $('#userAdd').on('click', function() {
            showUserDialog();
        });

        // 批量删除按钮
        $('#userDeleteBatch').on('click', function() {
            var checkStatus = table.checkStatus('userTable');
            var data = checkStatus.data;
            if (data.length === 0) {
                layer.msg('请选择要删除的数据', {icon: 2});
                return;
            }
            
            var ids = data.map(function(item) {
                return item.id;
            });
            
            layer.confirm('确定要删除选中的用户吗？', function(index) {
                $.post('/user/deleteBatch', {ids: ids}, function(res) {
                    if (res.code === 200) {
                        layer.msg('删除成功', {icon: 1});
                        tableIns.reload();
                    } else {
                        layer.msg(res.message || '删除失败', {icon: 2});
                    }
                }).fail(function() {
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                });
                layer.close(index);
            });
        });

        // 表格工具条事件
        table.on('tool(userTable)', function(obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                showUserDialog(data);
            } else if (obj.event === 'del') {
                layer.confirm('确定删除此用户？', function(index) {
                    $.post('/user/delete', {id: data.id}, function(res) {
                        if (res.code === 200) {
                            layer.msg('删除成功', {icon: 1});
                            obj.del();
                        } else {
                            layer.msg(res.message || '删除失败', {icon: 2});
                        }
                    }).fail(function() {
                        layer.msg('网络错误，请稍后重试', {icon: 2});
                    });
                    layer.close(index);
                });
            }
        });
    }

    function showUserDialog(data) {
        var title = data ? '编辑用户' : '新增用户';
        var userHtml = `
            <form class="layui-form" id="userForm" style="padding: 20px;">
                <input type="hidden" name="id" value="${data ? data.id : ''}">
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名" value="${data ? data.username : ''}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-block">
                        <input type="password" name="password" ${data ? '' : 'required lay-verify="required"'} placeholder="${data ? '不修改请留空' : '请输入密码'}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">真实姓名</label>
                    <div class="layui-input-block">
                        <input type="text" name="realName" placeholder="请输入真实姓名" value="${data ? data.realName : ''}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">手机号</label>
                    <div class="layui-input-block">
                        <input type="text" name="phone" lay-verify="phone" placeholder="请输入手机号" value="${data ? data.phone : ''}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">邮箱</label>
                    <div class="layui-input-block">
                        <input type="email" name="email" lay-verify="email" placeholder="请输入邮箱" value="${data ? data.email : ''}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">性别</label>
                    <div class="layui-input-block">
                        <input type="radio" name="gender" value="1" title="男" ${data && data.gender === 1 ? 'checked' : ''}>
                        <input type="radio" name="gender" value="0" title="女" ${data && data.gender === 0 ? 'checked' : ''}>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block">
                        <select name="status" lay-verify="required">
                            <option value="1" ${data && data.status === 1 ? 'selected' : ''}>启用</option>
                            <option value="0" ${data && data.status === 0 ? 'selected' : ''}>禁用</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">角色</label>
                    <div class="layui-input-block">
                        <select name="role" lay-verify="required">
                            <option value="0" ${data && data.role === 0 ? 'selected' : ''}>普通用户</option>
                            <option value="1" ${data && data.role === 1 ? 'selected' : ''}>管理员</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="address" placeholder="请输入地址" value="${data ? data.address : ''}" class="layui-input">
                    </div>
                </div>
            </form>
        `;

        var dialog = layer.open({
            type: 1,
            title: title,
            area: ['500px', '500px'],
            content: userHtml,
            btn: ['确定', '取消'],
            success: function(layero, index) {
                // 如果是编辑，设置选中值
                if (data) {
                    setTimeout(function() {
                        form.val('userForm', data);
                    }, 100);
                }
                
                form.render();
            },
            yes: function(index, layero) {
                var formData = form.val('userForm');
                
                // 如果是编辑且密码为空，删除密码字段
                if (formData.id && !formData.password) {
                    delete formData.password;
                }
                
                // 发送请求
                var url = formData.id ? '/user/update' : '/user/add';
                $.post(url, formData, function(res) {
                    if (res.code === 200) {
                        layer.msg(formData.id ? '修改成功' : '添加成功', {icon: 1});
                        layer.close(index);
                        tableIns.reload();
                    } else {
                        layer.msg(res.message || '操作失败', {icon: 2});
                    }
                }).fail(function() {
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                });
            }
        });
    }

    exports('user', { init: init });
}); 